package com.everflourish.yeah100.act.menu;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.GridLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.everflourish.yeah100.R;
import com.everflourish.yeah100.act.base.BaseFragment;
import com.everflourish.yeah100.adapter.QuestionBankAdapter;
import com.everflourish.yeah100.entity.question.QuestionTag;
import com.everflourish.yeah100.http.QuestionRequest;
import com.everflourish.yeah100.ui.AutoLoadRecylerView;
import com.everflourish.yeah100.utils.IntentUtil;
import com.everflourish.yeah100.utils.LogUtil;
import com.everflourish.yeah100.utils.MyToast;
import com.everflourish.yeah100.utils.constant.Constant;
import com.everflourish.yeah100.utils.constant.ResultCode;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.json.JSONArray;
import org.json.JSONObject;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

/**
 * 作者：Created by Administrator on 2016/6/1.
 * 时间：2016/6/1
 */
public class FragmentQuestion extends BaseFragment implements AutoLoadRecylerView.LoadMoreListener {

    public HomeActivity mActivity;
    private AutoLoadRecylerView mQuestionBankList;
    public SwipeRefreshLayout mSwipeRefreshLayout;
    public SwipeRefreshLayout.OnRefreshListener mRefreshListener;
    private List<QuestionTag> mList;
    private QuestionBankAdapter mAdapter;
    public QuestionRequest mRequest;
    private boolean isLoadMore = false;  // 是否加载更多
    private boolean isRefreshOrLoadMore = false;  // 是否在刷新或者加载
    public String tagName;

    /**
     * 每次加载10条
     */
    private int mSelectCount = 10;
    /**
     * 加载的位置
     */
    private int mStartIndex = 0;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_question, container, false);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initData();
        initWidget();
        configWidget();
    }

    private void initData() {
        mContext = mActivity = (HomeActivity) getActivity();
        mRequest = QuestionRequest.getInstance();
        mList = new ArrayList<QuestionTag>();
        mAdapter = new QuestionBankAdapter(mContext, mList, this);
    }

    private void initWidget() {
        mQuestionBankList = (AutoLoadRecylerView) getView().findViewById(R.id.question_bank_list);
        mSwipeRefreshLayout = (SwipeRefreshLayout) getView().findViewById(R.id.question_bank_swipe);
    }

    private void configWidget() {
        mQuestionBankList.setLayoutManager(new GridLayoutManager(getActivity(), 2));
        mQuestionBankList.setAdapter(mAdapter);
        mRefreshListener = new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                tagName = "";
                getQuestionBankList();
            }
        };
        mSwipeRefreshLayout.setColorScheme(R.color.colorPrimary);
        mSwipeRefreshLayout.setOnRefreshListener(mRefreshListener);
        mSwipeRefreshLayout.post(new Runnable() {
            @Override
            public void run() {
                mSwipeRefreshLayout.setRefreshing(true);
            }
        });
        mRefreshListener.onRefresh();
//        mQuestionBankList.setVisibility(View.GONE);
    }

    @Override
    public void onLoadMore() {
        isLoadMore = true;
        if (!isRefreshOrLoadMore) {
            getQuestionBankList();
        }
    }

    public void getQuestionBankList() {
        if (isLoadMore) {  // 加载更多
            mStartIndex = mStartIndex + mSelectCount;
        } else { // 下拉刷新
            mStartIndex = 0;
        }
        getQuestionBankListRequest(mStartIndex, mSelectCount, tagName);
    }

    /**
     * 获取题库请求
     *
     * @param startIndex
     * @param selectCount
     * @param name
     */
    private void getQuestionBankListRequest(int startIndex, int selectCount, String name) {
        isRefreshOrLoadMore = true;
        JsonObjectRequest request = mRequest.getQuestionTagListRequest(startIndex, selectCount, name,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        questionTagListListener(response);
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        mRequest.disposeError(mContext, mLoadDialog, error, "获取题库失败");
                        isRefreshOrLoadMore = false;
                        isLoadMore = false;
                        mSwipeRefreshLayout.post(new Runnable() {
                            @Override
                            public void run() {
                                mSwipeRefreshLayout.setRefreshing(false);
                            }
                        });
                        mQuestionBankList.setLoading(false);
                    }
                });
        mQueue.add(request);
    }

    /**
     * 获取题库监听
     *
     * @param response
     */
    private void questionTagListListener(JSONObject response) {
        int totalCount = 0;
        try {
            String resultCode = response.getString(Constant.RESULT_CODE);
            totalCount = response.getInt(Constant.TOTALCOUNT);
            if (resultCode.equals(ResultCode.result_ok.resultCode)) {
                JSONArray jsonArray = response
                        .getJSONArray(Constant.QUESTIONTAGS);
                Gson gson = new Gson();
                Type type = new TypeToken<List<QuestionTag>>() {
                }.getType();
                List<QuestionTag> questionTags = gson.fromJson(
                        jsonArray.toString(), type);
                if (questionTags.size() == 0) {
                    MyToast.showShort(mContext, "找不到相关的题目收藏");
                }
                if (!isLoadMore) {
                    mList.clear();
                }
                mList.addAll(questionTags);
                mAdapter.notifyDataSetChanged();
            } else if (resultCode.equals(ResultCode.result_000001E.resultCode)) {
                MyToast.showShort(mContext, R.string.questionlib_09171_000001E);
            } else if (resultCode.equals(ResultCode.result_300026E.resultCode)) {
                MyToast.showShort(mContext, R.string.questionlib_09174_300026E);
            } else if (resultCode.equals(ResultCode.result_system_exception_999999E)) {
                MyToast.showShort(mContext, R.string.questionlib_091799_999999E);
            } else {
                MyToast.showShort(mContext, "获取题库失败");
            }
        } catch (Exception e) {
            LogUtil.e("Json异常", e);
            MyToast.showShort(mContext, "获取题库失败");
        } finally {
//            mQuestionBankList.setVisibility(View.VISIBLE);
            mAdapter.notifyItemRangeInserted(0, mList.size() - 1);
            isLoadMore = false;
            mQuestionBankList.setLoading(false);
            isRefreshOrLoadMore = false;
            mSwipeRefreshLayout.post(new Runnable() {
                @Override
                public void run() {
                    mSwipeRefreshLayout.setRefreshing(false);
                }
            });
            if (mList.size() >= totalCount) {
                mQuestionBankList.setLoadMoreListener(null);
            } else {
                mQuestionBankList.setLoadMoreListener(this);
            }
        }
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void onPause() {
        super.onPause();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mQueue.stop();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == mActivity.RESULT_OK) {
            if (requestCode == 0x180) {
                if (data.getBooleanExtra(IntentUtil.QUESTION_IS_UPDATE, false)) {
                    mRefreshListener.onRefresh();
                }
            }
        }
    }
}
